package com.example.service;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.example.huashangapp.HSApplication;
import com.example.net.AnalyzingJson;
import com.example.net.NetRequest;
import com.example.ui.learn.DownUtils;
import com.example.ui.learn.ListeningActivity;
import com.example.util.Tools;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.net.Uri;
import android.os.Binder;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.IInterface;
import android.os.Message;
import android.os.Parcel;
import android.os.RemoteException;
import android.provider.MediaStore.Audio.Media;
import android.util.Log;
import android.widget.SeekBar;
import android.widget.Toast;

public class Mp3Service extends Service implements OnCompletionListener {
	private static final int CURRENTTIME = 1;
	public static MediaPlayer mp;
	private String id="" ;
	private Intent intent;
	// Handler handler;
	private int loopMode;
	private int musicId ;
	private Boolean islocal;
	private MyBinder binder=new MyBinder();
	private Handler handler;
	private ArrayList<String> list_mp3 = new ArrayList<String>();
	private String filepath;
	@Override
	public void onCreate() {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			filepath =Environment.getExternalStorageDirectory().toString()
					+ "/huashang/";
			Log.i("msg", "下载的路径"+filepath);
		}
		handler=HSApplication.handler;
		mp = new MediaPlayer();
		mp.setOnCompletionListener(this);
		mp.setOnSeekCompleteListener(new OnSeekCompleteListener() {
			@Override
			public void onSeekComplete(MediaPlayer mp) {
				//mp.start();
			}
		});
		mp.setOnErrorListener(new OnErrorListener() {
			@Override
			public boolean onError(MediaPlayer mp, int what, int extra) {
				Log.i("msg","播放错误"+id);
				if (mp != null) {
					mp.release();
				}
				return false;
			}
		});
		super.onCreate();
	}
	@Override
	public void onStart(Intent intent, int startId) {
		if(intent!=null){
			String URI = intent.getStringExtra("uri");
			// 获得循环模式
			int mode = intent.getIntExtra("mode", -1);
			String newURI=isNetUrl(URI);
			if("".equals(newURI)){
				return;
			}
			Log.i("msg","mp执行播放方法"+musicId+"之前的id"+id+"连接"+URI);
			if (id != URI&&mp!=null) {
					id = URI;
					mp.reset();
					try {
						Uri uri = Uri.parse(newURI);
						if (!islocal) {
							mp.setDataSource(this, uri);//网络
						} else {
							mp.setDataSource(newURI);//本地
						}
						mp.prepare();
					} catch (Exception e) {
						e.printStackTrace();
					}
			}
			
			switch (mode) {
			case Tools.STOP:
				stop();
			case Tools.PLAY:
				play();
				break;
			case Tools.PAUSE:
				pause();
				break;
			case Tools.PROGRESS:
				int progress = intent.getIntExtra("progress", -1);
				mp.seekTo(progress);
				break;
			default:
				break;
			}
			}
}

	private void stop() {

		if (mp != null) {
			mp.stop();
			removeHandler();
		}
	}

	// 发送当前播放时间消息，发送总时间的广播
	private void setUp() {
		mp.setOnPreparedListener(new OnPreparedListener() {
			@Override
			public void onPrepared(MediaPlayer mp) {
				handler.sendEmptyMessage(CURRENTTIME);
			}
		});

	}
	public void removeHandler() {
		handler.removeMessages(CURRENTTIME);
	}

	private void pause() {
		if (mp != null) {
			mp.pause();
			removeHandler();
		}
	}

	private void play() {
		if (mp != null) {
			mp.start();
			setUp();
		}
	}

	@Override
	public void onDestroy() { 
		if (mp != null) {
			mp.release();
		}
		super.onDestroy();
	}

	@Override
	public IBinder onBind(Intent intent) {
		return this.binder;
	}

	public void setLoopMode(int mode) {
		this.loopMode = mode;
	}

	// 播放完毕后执行的功能
	@Override
	public void onCompletion(MediaPlayer mp) {
		Message msg=new Message();
		msg.what=2;
		handler.sendMessage(msg);
	}
	private  void onStartMP3(Intent intent){
		onStart(intent,0);
	}
	public class MyBinder extends Binder{
	   public void startMp3Service(Intent intent){
			onStartMP3(intent);
		}
	   public void stopMP3(){
		  stop();
	   }
	}
	public String isNetUrl(String url){
		if(url==null){
			return "";
		}
		String lisname= url.substring(url.lastIndexOf("/") + 1);
		File f = new File(filepath);
		if (f.exists()) {
			searchFiles(f);
		}
		for (int i = 0; i < list_mp3.size(); i++) {
			if (lisname.equals(list_mp3.get(i))) {
				islocal=true;
				return filepath+lisname;
			} else {
				islocal=false;
				return url;
			}
		}
		for (String file : DownUtils.downUrl) {
			if(file==null){
				continue;
			}
			String Downname= file.substring(file.lastIndexOf("/") + 1);
			if(lisname.equals(Downname)){
				islocal=false;
				return url;
				}			
			}
		return url;
	}

	private void searchFiles(File f) {
		list_mp3.clear();
		
		File files[] = f.listFiles();
		for (File tempF : files) {
			if(tempF==null){
				continue;
			}
			if (tempF.isDirectory()) {
				searchFiles(tempF);
			} else {
				String path = tempF.getPath();
				String fpath = path.substring(path.lastIndexOf(".") + 1,
						path.length());
				if (fpath.equals("mp3")) {
					String mp3 = path.substring(path.lastIndexOf("/") + 1);
					list_mp3.add(mp3);
				}
			}
		}
	}
	
}
